<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Session;

class Index extends Controller
{
    protected function _initialize()
    {
        $user = Session::get('Muser');
        if(!$user){
            $this->redirect('/admin/login');
        }
    }

    public function index()
    {
        $chuser=Db::name('character')
            ->where('ch_state',1)
            ->select();
        $this->assign('chuser',$chuser);
        return $this->fetch('index/reuser');
    }

    public function deluser()
    {
        $chid=$_GET['chid'];
        Db::name('character')
            ->where('ch_id',$chid)
            ->delete();
        $this->success('删除成功', '/admin');
    }

    public function adduser()
    {
        $group=Db::name('group')
            ->select();
        $this->assign('group',$group);
        return $this->fetch('index/adduser');
    }

    public function add_do()
    {
        $userinfo=input('post.');
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('chimg');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->move( '../public/upload');
        if($info){
            // 成功上传后 获取上传信息
            // 输出 jpg
            /*echo $info->getExtension();
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            echo $info->getSaveName();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
            echo $info->getFilename();*/
            $imgurl=$info->getSaveName();
            $data = [
                'ch_name' => $userinfo['chname'],
                'ch_img' => '/upload/'.$imgurl,
                'ch_gid' => $userinfo['group']
            ];
            Db::name('character')->insert($data);
            $this->success('新增成功', '/admin');

        }else{
            // 上传失败获取错误信息
            echo $file->getError();
        }

    }

    public function eduser()
    {
        $chid=$_GET['chid'];
        $chuser=Db::name('character')
            ->where('ch_id',$chid)
            ->find();
        //$this->success('删除成功', '/admin');
        $this->assign('chuser',$chuser);
        return $this->fetch('index/eduser');
    }

    public function edit_do()
    {
        $userinfo=input('post.');
        Db::name('character')
            ->where('ch_id', $userinfo['chid'])
            ->update(['ch_name' => $userinfo['chname'],'ch_click' => $userinfo['chclick']]);
        $this->success('更新成功', '/admin');
    }
}
